<?php
require_once APP . '/application/controllers/FrontAction.php';
require_once APP . '/application/models/MeetModel.php';

/**
 * 后台管理主页
 * @package admin
 */
class IndexController extends FrontAction
{
    

    public function init()
    {
        // $this->_config = Registry::get ('config');
    }
    
    /**
     * 首页处理
     */
    public function indexAction()
    {
    	// 1 读取图片新闻
    	$arr_image_list = $this->db->fetchAll("select * from article where cid={$this->cfg['platcid']} order by seq desc, aid desc limit 5");
    	
    	// 2,读取近期召开会议
    	$s_diff_month = (int)$this->db->fetchOne("select value from platset where name='plat_meet'");
    	$s_time = date("Y-m-d 59:59:59", strtotime("{$s_diff_month} month"));
    	$s_ctime = date("Y-m-d 00:00:00");
    	$sql = "select * from meet where startdate<'{$s_time}' and enddate>='{$s_ctime}' and status=3 and public=1 order by startdate asc limit 3";
    	$arr_recent_list = $this->db->fetchAll($sql);
    	foreach($arr_recent_list as $k => $v){
    		$arr_recent_list[$k]['url'] = $this->view->fullUrl . '/' . $v['domain'];
    	}
    	
    	// 3,读取最近发布会议
    	$sql = "select * from meet where status=3 and public=1 order by createtime desc limit 3";
    	$arr_pub_list = $this->db->fetchAll($sql);
    	foreach($arr_pub_list as $k => $v){
    		$arr_pub_list[$k]['url'] = $this->view->fullUrl . '/' . $v['domain'];
    	}
    	
    	$this->view->list_image = $arr_image_list;
    	$this->view->list_recent = $arr_recent_list;
    	$this->view->list_pub = $arr_pub_list;
		$this->view->select = "index";
    	
    	$this->render("index");
    }
    
    /**
     * 文章
     */
    public function articleAction()
    {
    	$key = $this->getParam("t");
    	
    	if ($key != 'about' && $key != 'help'){
    		exit;
    	}
    	
    	$aid = (int)$this->db->fetchOne("select value from platset where name='plat_{$key}'");
    	$content = $this->db->fetchOne("select content from article where aid={$aid}");
    	
    	$this->view->content = $content;
    	$this->view->key = $key;
    	
    	if ($key == 'help')
    		$this->view->htitle = "帮助中心";
    	else
    		$this->view->htitle = "关于我们";
    	
    	$this->view->select = $key;
    	
    	$this->render('article');
    }
    
    /**
     * 会议查询
     */
    public function listAction()
    {
		$t = (int)$this->getParam("t", 1);
		$year =(int)$this->getParam("year");
		$query = $this->getParam("query");
		
		$nowp = (int)$this->getParam("nowp");
		$per_page = 10;
		
		if (!empty($t)){
			$startdate = date("Y-m-d 00:00:00");
			$enddate = date("Y-m-d 23:59:59", strtotime("+{$t} month"));
		}
		if (!empty($year)){
			$startdate = "{$year}-00-00 00:00:00";
			$enddate = "{$year}-12-31 23:59:59";
		}
		
		// 查询年份列表
		$arr_year = $this->db->fetchAll("select DISTINCT YEAR(startdate) `year` from meet");
		
		$obj = new MeetModel($this->db);
		
		$result = $obj->fetchIndexAll($query, $startdate, $enddate, $nowp, $per_page);
		
		foreach($result['list'] as $k => $v){
			$result['list'][$k]['url'] = $this->view->fullUrl . '/' . $v['domain'];
		}
		

		$this->view->t = $t;
		$this->view->year = $year;
		$this->view->query = $query;
		$this->view->arr_year = $arr_year;
		
		$this->view->list = $result['list'];
    	$this->view->page = $result['page'];
    	$this->view->pagenum = Util::pageNumStyle($result['page']);
		
    	$this->view->htitle = "会议查询";
    	$this->view->select = "list";
    	
    	$this->render("list");
    }
    
    
    /**
     * 注册登录模块
     */
    public function regloginAction()
    {
    	$gourl = $this->getParam("gourl");
    	$debug = $this->getParam("d");
    	
    	if (empty($gourl)){
    		$gourl = $this->view->fullUrl;
    	}
    	
    	// 国家或地区读取
    	$nations = $this->db->fetchOne("select value from platset where name='plat_cn_nations'");
    	$arr_nations = explode("\n", $nations);
    	foreach($arr_nations as $index => $v){
    		$arr_nations[$index] = trim($v);
    		if (empty($arr_nations[$index])){
    			unset($arr_nations[$index]);
    		}
    	}
    	    	
    	$this->view->debug = $debug != NULL?true:false;
    	$this->view->nations = $arr_nations;
    	$this->view->dnation = $this->db->fetchOne("select value from platset where name='plat_cn_def_nation'");;
    	$this->view->gourl = $gourl;
    	
    	$this->view->htitle = "注册登录";
    	$this->view->css_files = array("js/jquery-ui/jquery-ui-1.8.16.custom.css");
    	$this->render("reglogin");
    }
    
    
    /**
     * 修改用户信息
     */
    public function chginfoAction()
    {
    	$uid = (int)$_SESSION['uid'];
    	
    	$uinfo = $this->db->fetchRow("select * from user where uid=?", array($uid));
    	
    	// 国家或地区读取
    	$nations = $this->db->fetchOne("select value from platset where name='plat_cn_nations'");
    	$arr_nations = explode("\n", $nations);
    	foreach($arr_nations as $index => $v){
    		$arr_nations[$index] = trim($v);
    		if (empty($arr_nations[$index])){
    			unset($arr_nations[$index]);
    		}
    	}
    	
    	$this->view->nations = $arr_nations;
    	 
    	$this->view->uinfo = $uinfo;
    	$this->view->htitle = "修改用户信息";
    	$this->view->css_files = array("js/jquery-ui/jquery-ui-1.8.16.custom.css");
    	$this->render("chginfo");
    }
    
    
    /**
     * 上传文件
     */
    public function uploadAction()
    {    	
    	$type = $this->getParam("t");
    	$plan = $this->getParam("plan");
    	
    	if ($type != 'head' && $type != 'idcode')
    		exit("error type");
    	
    	/**************图片处理*********************/
    	$image = "";
    	if (!empty($_FILES) && !empty($_FILES['image']) && !empty($_FILES['image']['name'])){
    		$file_ext = pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION);
    		$todir = APP . '/upload';
    		if (!file_exists($todir . '/image'))
    			mkdir($todir . '/image');
    		if (!file_exists($todir . '/image/' . date("Ymd")))
    			mkdir($todir . '/image/' . date("Ymd"));
    	
    		// 缩略图处理
    		list($width, $height, $im_type, $attr) = getimagesize($_FILES['image']['tmp_name']);
    		$im = null;
    		switch($im_type){
    			case IMAGETYPE_JPEG:
    			case IMAGETYPE_JPEG2000:
    				$im = imagecreatefromjpeg($_FILES['image']['tmp_name']);
    				break;
    			case IMAGETYPE_PNG:
    				$im = imagecreatefrompng($_FILES['image']['tmp_name']);
    				break;
    			default:
    				break;
    		}
    		
    		$image_pre = '/upload/image/' . date("Ymd") . '/' .date("YmdHis") . '_' . uniqid("h");
    		
    		if ($im != null){
    			$newimg = imagecreatetruecolor(54, 54);
    			imagecopyresampled ( $newimg, $im, 0, 0, 0, 0, 54, 54, imagesx($im), imagesy($im) );
    			imagejpeg($newimg, APP . $image_pre . '_tb.jpg');
	    		
	    		$image = $image_pre . '.' . $file_ext;
	    		move_uploaded_file($_FILES['image']['tmp_name'], APP . $image);
	    		
	    		$result = array("status" => 1, "tbimage" => $image_pre . '_tb.jpg', "image" => $image);
    		}else{
    			if ($plan == 'en')
    				$result = array("status" => 0, 'message' => 'Upload failed! Only supports JPG, PNG format');
    			else
    				$result = array("status" => 0, 'message' => '上传失败！只支持jpg、png格式');
    		}
    		
    		$this->view->result = $result;
    	}
    	
    	
    	$this->view->plan = $plan;
    	$this->view->type = $type;
    
    	$this->render("reg_file_pho");
    }

    
    /**
     * 注册逻辑
     *
     */
    public function doregAction()
    {
    	$email = $this->getPost("email", "");
    	$email = strtolower($email);
    	$password = $this->getPost("password", "");
    	$password2 = $this->getPost("password2", "");
    	$plan = $this->getParam("plan");
    	
    	$arr_langs = array();
    	$arr_lans['tip1'] = 'E-mail必须填写！';
    	$arr_lans['tip2'] = '密码必须填写！';
    	$arr_lans['tip3'] = '两次密码不一致！';
    	$arr_lans['tip4'] = 'E-mail格式不正确！';
    	$arr_lans['tip5'] = 'E-mail已注册，请更换E-mail！';
    	$arr_lans['tip6'] = '注册失败！请重试。';
    	
    	if ($plan == 'en'){
    		$arr_lans['tip1'] = 'E-mail is required.';
    		$arr_lans['tip2'] = 'Passport is required.';
    		$arr_lans['tip3'] = 'Two passwords can\'t match.';
    		$arr_lans['tip4'] = 'The format of E-mail isn\'t correct.';
    		$arr_lans['tip5'] = 'The email is already registered. Please use another one.';
    		$arr_lans['tip6'] = 'Registration is failed. Please try it again.';
    	}
    	
    	if (empty($email))
    		$this->showmessage($arr_lans['tip1']);
    		    	
    	if (empty($password))
    		$this->showmessage($arr_lans['tip2']);
    	
    	if ($password != $password2)
    		$this->showmessage($arr_lans['tip3']);
    		    	    	    	
    	 if (!ereg("^([\.a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+",$email))
    	 	$this->showmessage($arr_lans['tip4']);
    	     	 	
    	require_once(APP . '/application/models/UserModel.php');
    	require_once(APP . '/application/models/Util.php');
    	$obj_user = new UserModel($this->db);
    	
    	if ($obj_user->isEmailReg($email))
    	{
    		$this->showmessage($arr_lans['tip5']);
    	}
    	
    	global $cfg;
    	$params = $this->getAllParams();
    	foreach ($params as $key => $v){
    		$params[$key] = trim($v);
    	}
    	
    	$params['password'] = md5(md5($params['password']) . $cfg['slot']);
    	
    	$params['regip'] = Util::getip(true);
    	$params['regtime'] = date("Y-m-d H:i:s");
    	
    	try{
    		$uid = $obj_user->add($params);
    		$_SESSION['uid'] = $uid;
    		$result = array("status" => 1);
    	}catch (Exception $e){
    		$result = array("status" => 0, "message" => $arr_lans['tip6']);
    	}
    	
    	$result['gourl'] = $this->getParam("gourl");
    	echo json_encode($result);
    }
    
    

    /**
     * 修改用户逻辑
     *
     */
    public function dochangeAction()
    {
    	$uid = (int)$_SESSION['uid'];
    	$mid = (int)$this->getParam("mid");
    	$plan = $this->getParam("plan");
    	 
    	$arr_langs = array();
    	$arr_lans['tip1'] = '账号必须填写！';
    	$arr_lans['tip2'] = '您已做了最终确认，所有信息不可修改。';
    	$arr_lans['tip3'] = '修改失败！请重试。';
    	 
    	if ($plan == 'en'){
    		$arr_lans['tip1'] = 'Account is required.';
    		$arr_lans['tip2'] = 'You have done final confirmation. All information cannot be modified.';
    		$arr_lans['tip3'] = 'Modification is failed. Please try it again.';
    	}
    	
    	if (empty($uid)){
    		$this->showmessage($arr_lans['tip1']);
    	}
    	    	     	 
    	require_once(APP . '/application/models/UserModel.php');
    	require_once(APP . '/application/models/Util.php');
    	$obj_user = new UserModel($this->db);
    	 
    	global $cfg;
    	$params = $this->getAllParams();
    	foreach ($params as $key => $v){
    		$params[$key] = trim($v);
    	}
    	 
    	unset($params['password']);
    	
    	$ischeck = $this->db->fetchOne("select ischeck from meetuser where mid=? and uid=?", array($mid, $uid));
    	
    	if ($ischeck == 4){
    		$result = array("status" => 0, "message" => $arr_lans['tip2']);
    		echo json_encode($result);
    		exit;
    	}
    	
    	try{
    		$uid = $obj_user->change($uid, $params);
    		$result = array("status" => 1);
    	}catch (Exception $e){
    		$result = array("status" => 0, "message" => $arr_lans['tip3']);
    	}
    	 
    	$result['gourl'] = $this->getParam("gourl");
    	if (!empty($mid)){
    		$domain = $this->db->fetchOne("select domain from meet where mid=?", array($mid));
    		$result['gourl'] = $this->view->fullUrl .'/'. $domain . '?a=muinfo';
    	}
    	echo json_encode($result);
    }
    
    
    /**
     * 账号检测
     *
     */
    public function mailcheckAction()
    {
    	$email = $this->getPost("email");
    	
    	$plan = $this->getParam("plan");
    	
    	$arr_langs = array();
    	$arr_lans['tip1'] = 'E-mail必须填写！';
    	$arr_lans['tip2'] = 'E-mail格式不正确！';
    	$arr_lans['tip3'] = '该E-mail已注册！';
    	
    	if ($plan == 'en'){
    		$arr_lans['tip1'] = 'E-mail is required.';
    		$arr_lans['tip2'] = 'The format of email isn\'t correct.';
    		$arr_lans['tip3'] = 'The email is already registered.';
    	}
    	
    	require_once(APP . '/application/models/UserModel.php');
    	$user = new UserModel($this->db);
    	
    	if (empty($email))
    		$this->showmessage($arr_lans['tip1']);
    	
    	if (!ereg("^([\.a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+",$email))
    	 	$this->showmessage($arr_lans['tip2']);
    	 
    	if ($user->isEmailReg($email))
    	{
    		$this->showmessage($arr_lans['tip3']);
    	}
    	
    	echo '{"status:1"}';
    }
    
    /**
     * 显示验证码,不需验证
     * @author RD
     */
    public function authcodeAction ()
    {
    	$this->setAutoRender (false);
    
    	require_once APP . '/application/models/Util.php';
    	$rstr = array ('a','b','c','d','e','f','g','h','j','k','m','n','o','p','r','s','t','u','v','w','x','y','z',
    			'A','B','C','D','E','F','G','H','J','K','M','N','O','P','R','S','T','U','V','W','X','Y','Z');
    
    	//验证码
    	$authcode = $_SESSION['u_authcode'] = $rstr[array_rand ($rstr, 1)] . $rstr[array_rand ($rstr, 1)].$rstr[array_rand ($rstr, 1)]. $rstr[array_rand ($rstr, 1)];
    
    	//输出图片
    	/**
    	 Header ('Expires', '-1', true);
    	 Header ('Cache-Control', 'no-store, private, post-check=0, pre-check=0, max-age=0', true);
    	 Header ('Pragma', 'no-cache', true);
    	 Header ('Content-type', 'image/jpeg', true);
    	 **/
    	$im  = Util::createJpeg ($authcode, APP . '/application/configs/COPRGTB.TTF');
    	imageJpeg ($im);
    	imagedestroy ($im);
    }
    
    /**
     * 登录逻辑
     */
    public function loginAction()
    {
    	$email = trim($this->getPost("email"));
    	$password = trim($this->getPost("password"));
    	$authcode = trim($this->getPost("authcode"));
    	
    	$plan = $this->getParam("plan");
    	 
    	$arr_langs = array();
    	$arr_lans['tip1'] = 'E-mail或者密码必须填写！';
    	$arr_lans['tip2'] = '验证码必须填写！';
    	$arr_lans['tip3'] = '验证码错误！';
    	$arr_lans['tip4'] = '账号不存在！';
    	$arr_lans['tip5'] = '账号密码错误！';
    	 
    	if ($plan == 'en'){
    		$arr_lans['tip1'] = 'E-mail or password is required.';
    		$arr_lans['tip2'] = 'Verification code is required.';
    		$arr_lans['tip3'] = 'Verification code is incorrect.';
    		$arr_lans['tip4'] = 'Account doesn\'t exist.';
    		$arr_lans['tip5'] = 'Account or password is incorrect.';
    	}
    	
    	if (empty($email) || empty($password))
    		$this->showmessage($arr_lans['tip1']);
    	
    	if (empty($authcode)){
    		$this->showmessage($arr_lans['tip2']);
    	}
    	
    	if (strtolower($_SESSION['u_authcode']) != strtolower ($authcode)){
    		$_SESSION['u_authcode'] = mt_rand();
    		$this->showmessage($arr_lans['tip3'], 1000);
    	}
    	
    	require_once(APP . '/application/models/UserModel.php');
    	$user = new UserModel($this->db);
    	
    	$row = $user->showByMail($email);
    	
    	if (empty($row)){
    		$this->showmessage($arr_lans['tip4']);
    	}
    	
    	global $cfg;
    	$pwd = md5(md5($password) . $cfg['slot']);
    	if ($row['email'] != $email || $row['password'] != $pwd){
    		$_SESSION['u_authcode'] = mt_rand();
    		$this->showmessage($arr_lans['tip5'], 1000);
    	}
    	
    	$_SESSION['uid'] = $row['uid'];
    	
    	$result = array("status" => 1);
    	$result['gourl'] = $this->getParam("gourl");
    	
    	echo json_encode($result);
    }
    
    /**
     * 忘记密码
     *
     */
    public function findAction()
    {
    	global $cfg;
    	$email = $this->getPost("email", "");
    	$plan = $this->getParam("plan");
		$mname = $this->getPost("m_name", "");
    	
    	$arr_langs = array();
    	$arr_lans['tip1'] = 'E-mail必须填写！';
    	$arr_lans['tip2'] = 'E-mail不存在！';
    	if (empty($mname)) $arr_lans['tip3'] = $cfg['title'] . " - 找回密码";
		else $arr_lans['tip3'] = $mname. '会议注册系统 - 找回密码';
		//$arr_lans['tip3'] = $cfg['title'] . " - 找回密码";
    	$arr_lans['tip4'] = "您的E-mail为：";
    	$arr_lans['tip5'] = "<br />您的新密码为：";
    	$arr_lans['tip6'] = '邮件发送失败！请联系管理员。';
    	$arr_lans['tip7'] = '密码已经发送到您的邮箱，请查收。';
    	 
    	if ($plan == 'en'){
    		$arr_lans['tip1'] = 'E-mail is required.';
    		$arr_lans['tip2'] = 'E-mail doesn\'t exist.';
			if(empty($mname)) $arr_lans['tip3'] = "Conference Service Platform - Find Password";
			else $arr_lans['tip3'] = $mname. ' Conference Service Platform - Find Password';
	    	$arr_lans['tip4'] = "Your E-mail：";
	    	$arr_lans['tip5'] = "<br />Your new password：";
	    	$arr_lans['tip6'] = 'Mail delivery failed! Please contact the administrator.';
	    	$arr_lans['tip7'] = 'The password has been sent to your mailbox, please check it.';
    	}
    	
    	if (empty($email))
    		$this->showmessage($arr_lans['tip1']);
    	
    	$exist = $this->db->fetchOne("select count(*) from user where email='?'", array($email));
    	if (!$exist)
    		$this->showmessage($arr_lans['tip2']);
    	    	
    	$newpw = substr(md5(uniqid("user")), mt_rand(0, 5), mt_rand(10,15));
    	$pwd = md5(md5($newpw) . $cfg['slot']);
    	$this->db->update("user", array("password" => $pwd), $this->db->quoteInto("email='?'", array($email)));
    	
    	$mid = (int)$this->getParam("mid");
    	if (!empty($mid)){
    		$arr_minfo = $this->db->fetchRow("select * from meet where mid=?", array($mid));
    	}
    	// 发送邮件
    	require_once APP . '/application/models/mail/class.phpmailer.php';
    	ob_start();
    	$mail = new PHPMailer();

		if ($this->cfg['debug'])
			$mail->SMTPDebug = 2;
		
		require_once(APP . '/application/models/PlatsetModel.php');
		$set = new PlatsetModel($this->db);
		$set_mail = $set->getmulti(array("plat_email", "plat_emailuser", "plat_emailpwd", 'plat_smtpserver'));
		
		if (!empty($arr_minfo)){
			$set_mail['plat_smtpserver'] = $arr_minfo['smtpserver'];
			$set_mail['plat_email'] = $arr_minfo['email'];
			$set_mail['plat_emailpwd'] = $arr_minfo['emailpwd'];
			$set_mail['plat_emailuser'] = $arr_minfo['emailuser'];			
		}
		
		$mail->SMTPKeepAlive = true;
		$mail->IsSMTP();					// 启用SMTP
		$mail->Host = $set_mail['plat_smtpserver'];			//SMTP服务器
		$mail->SMTPAuth = true;		//开启SMTP认证
		$mail->Username = $set_mail['plat_email'];		// SMTP用户名
		$mail->Password = $set_mail['plat_emailpwd'];	// SMTP密码
		$mail->From = $set_mail['plat_email'];			//发件人地址
		$mail->FromName = $set_mail['plat_emailuser'];;				//发件人
		
		$mail->WordWrap = 80;					//设置每行字符长度
		
		$mail->CharSet = "utf-8";				// 这里指定字符集！
		$mail->Encoding = "base64"; 
		$mail->IsHTML(true);					// 是否HTML格式邮件
		
		$mail->AddAddress($email);
		$mail->Subject = $arr_lans['tip3'];			//邮件主题
		$content = $arr_lans['tip4'] . $email . $arr_lans['tip5'] . $newpw;
		$mail->Body = $content;
		if(!$mail->Send()){			
			$log = ob_get_contents();
			ob_end_clean();
			
		   $err =  print_r($set_mail, true). "Message could not be sent.<$email> <p>\n" . 
		   "Mailer Error: " . $mail->ErrorInfo . "\nLOG:" . $log . "\n\n";
		   file_put_contents(APP . '/cache/pwd.log', $err,FILE_APPEND);
		   $this->showmessage($arr_lans['tip6']);
		}
		
		$mail->SmtpClose();
		$log = ob_get_contents();
		ob_end_clean();
		
		if (!empty($log))
			file_put_contents(APP . '/cache/pwd.log', $log,FILE_APPEND);
		
		
		$result = array("status" => 1, "message" => $arr_lans['tip7']);
		echo json_encode($result);
    }
    
    /**
     * 注销
     */
    public function logoutAction()
    {
    	unset($_SESSION['uid']);
    	
    	$gourl = $this->getParam("gourl");
    	
    	if (!empty($gourl)){
    		header("location:" . $gourl);
    	}else
    		$this->redirectAction("index", "index");
    }
    
    /**
     * 修改密码
     */
    public function chgpwdAction()
    {
    	$this->render("chgpwd");
    }
    
    /**
     * 修改密码
     */
    public function dochangepwdAction()
    {
    	global $cfg;
		
    	$uid = (int)$_SESSION['uid'];
    	
    	$password = $this->getParam("password");
    	$oldpassword = $this->getParam("oldpassword");
    	
    	if (empty($uid)){
    		$this->showmessage("您还未登录！");
    	}
    	
    	require_once(APP . '/application/models/UserModel.php');
    	$user = new UserModel($this->db);
    	 
    	$row = $user->show($uid);
    	
    	$old = md5(md5($oldpassword) . $cfg['slot']);
    	if ($old != $row['password']){
    		if ($this->getParam("plan") == 'en')
    			$this->showmessage("Original password is incorrect.");
    		else
    			$this->showmessage("原始密码错误！");
    	}
    	
    	$new = md5(md5($password) . $cfg['slot']);
    	$user->change($uid, array("password" => $new));
    	
    	echo '{"status":1}';
    }
}